#!/bin/bash
set -e

echo "=== 1. 安装必要工具 ==="
sudo apt update -y
sudo apt install -y curl gnupg lsb-release apt-transport-https ca-certificates

echo "=== 2. 安装 Docker（阿里云镜像） ==="
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

echo "=== 3. 配置 Docker 国内加速器 ==="
sudo mkdir -p /etc/docker
cat <<JSON | sudo tee /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://docker.m.daocloud.io",
    "https://hub-mirror.c.163.com",
    "https://mirror.ccs.tencentyun.com",
    "https://registry.docker-cn.com",
    "https://dockerproxy.com"
  ]
}
JSON

echo "=== 4. 重启 Docker 服务 ==="
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo systemctl enable docker

echo "=== 5. 安装 Docker Compose 插件 ==="
sudo apt install -y docker-compose-plugin

echo "=== 6. 将当前用户加入 docker 组（免 sudo） ==="
sudo usermod -aG docker $USER

echo "=== 7. 切换到 docker 组（免 sudo 立即生效）==="
newgrp docker <<EONG

echo "=== 8. 验证 Docker 是否可用 ==="
docker run --rm hello-world

echo "=== 9. 验证 docker compose 是否可用 ==="
docker compose version

EONG

echo "=== 完成！Docker 和 docker compose 安装并验证成功 ==="
